package com.yuan.zsschool.ui.wonderful;

import android.content.Context;
import android.content.Intent;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuan.base.framework.BaseFrameworkFragment;
import com.yuan.base.framework.BaseViewHolderAdapter;
import com.yuan.base.framework.bean.TipResult;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.framework.image.BaseImageLoad;
import com.yuan.base.utils.DateUtil;
import com.yuan.base.widget.AutoLoadList;
import com.yuan.base.widget.inlist.NoScrollListView;
import com.yuan.zsschool.R;
import com.yuan.zsschool.Urls;
import com.yuan.zsschool.bean.Comment;
import com.yuan.zsschool.bean.School;
import com.yuan.zsschool.bean.Wonderful;
import com.yuan.zsschool.common.CacheManager;
import com.yuan.zsschool.common.PrefCache;
import com.yuan.zsschool.ui.ShowImageActivity;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


public class WonderfulFragment extends BaseFrameworkFragment implements Serializable {

	// --------------------------控件--------------------------
	private AutoLoadList auto_load_list;
	private ListView data_list;// 下拉刷新
	// --------------------------变量--------------------------
	private List<Wonderful> dataList;
	private WonderfulAdapter wonderfulAdapter;
	private int index = 0;
	private int type = 1;// 1视频 2图片

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_wonderful;
	}

	@Override
	protected void bindViews() {

		auto_load_list = findViewById(R.id.auto_load_list);
		data_list = auto_load_list.getData_list();
		auto_load_list.setNeedShowFooter(false);
		auto_load_list.setOnRefreshingListener(new AutoLoadList.OnRefreshingListener() {
			@Override
			public void onRefresh() {
				getListData(AutoLoadList.OPT_REFREASH);
			}

			@Override
			public void onLoadMore() {
				getListData(AutoLoadList.OPT_LOADMORE);
			}
		});

		data_list.setOnItemClickListener((parent, view, position, id) -> {
//			Intent intent = new Intent(this, NoticeDetailActivity.class);
//			intent.putExtra("notice", (Notice) parent.getItemAtPosition(position));
//			startActivity(intent);
		});
	}

	@Override
	protected void initUI() {
		auto_load_list.startRefreshing();
	}

	public void setType(int type) {
		this.type = type;
	}

	private void getListData(final int opt) {
		if (opt == AutoLoadList.OPT_INIT || opt == AutoLoadList.OPT_REFREASH) {
			index = 0;
		}
		if (opt == AutoLoadList.OPT_LOADMORE) {
			index++;
		}

		String url = Urls.getUrl(Urls.getWonderfulVideoList);
		if (type == 2) {
			url = Urls.getUrl(Urls.getWonderfulImageList);
		}

		HashMap<String, Object> params = new HashMap<>();
		params.put("page", index);
		params.put("size", auto_load_list.getRowCount());
		BaseHttpRequest.get(url, params, new BaseHttpCallBack<JSONObject>() {
			@Override
			public void onSuccess(JSONObject result) {
				if (result != null && result.containsKey("content")) {
					List<Wonderful> imageList = JSON.parseArray(result.getString("content"), Wonderful.class);
					for (int i = 0; i < imageList.size(); i++) {
						imageList.get(i).setType(type);
					}
					switch (opt) {
						case AutoLoadList.OPT_INIT:
						case AutoLoadList.OPT_REFREASH:
							dataList = imageList;
							init(true);
							break;
						case AutoLoadList.OPT_LOADMORE:
							dataList.addAll(imageList);
							init(false);
							break;
					}
				}
			}

			@Override
			public void onPost() {
				auto_load_list.completeRefresh();
			}
		});

	}

	private void init(boolean needNew) {
		if (needNew) {
			wonderfulAdapter = new WonderfulAdapter(context);
			wonderfulAdapter.setData(dataList);
			data_list.setAdapter(wonderfulAdapter);
		} else {
			wonderfulAdapter.setData(dataList);
			wonderfulAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onResume() {
		super.onResume();
	}


	@Override
	public void onStart() {
		super.onStart();
	}

	private void doZan(int id, ImageView imageView) {
		if (imageView.isSelected()) {
			showToast("您已赞过，不能重复赞");
			return;
		}
		HashMap<String, Object> params = new HashMap<>();
//		params.put("pushId", id);
//		params.put("type", type == 1 ? "video" : "image");
		String paStr = "?pushId=" + id + "&type=" + (type == 1 ? "video" : "image");
		BaseHttpRequest.post(Urls.getUrl(Urls.doZan + paStr), params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					showToast("点赞成功");
					PrefCache.setZan(true, id, type);
					imageView.setSelected(true);
					for (int i = 0; i < dataList.size(); i++) {
						if (dataList.get(i).getId() == id) {
							dataList.get(i).setPositives(dataList.get(i).getPositives() + 1);
							wonderfulAdapter.notifyDataSetChanged();
							break;
						}
					}
				} else {
					showToast("点赞失败");
				}
			}
		});
	}

	private void doCai(int id, ImageView imageView) {
		if (imageView.isSelected()) {
			showToast("您已踩过，不能重复踩");
			return;
		}
		HashMap<String, Object> params = new HashMap<>();
//		params.put("pushId", id);
//		params.put("type", type == 1 ? "video" : "image");
		String paStr = "?pushId=" + id + "&type=" + (type == 1 ? "video" : "image");
		BaseHttpRequest.post(Urls.getUrl(Urls.doCai + paStr), params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					showToast("踩成功");
					PrefCache.setCai(true, id, type);
					imageView.setSelected(true);
					for (int i = 0; i < dataList.size(); i++) {
						if (dataList.get(i).getId() == id) {
							dataList.get(i).setNegatives(dataList.get(i).getNegatives() + 1);
							wonderfulAdapter.notifyDataSetChanged();
							break;
						}
					}
				} else {
					showToast("踩失败");
				}
			}
		});
	}

	private void doComment(int id, String content) {
		HashMap<String, Object> params = new HashMap<>();
		params.put("pushId", id);
		params.put("content", content);
		BaseHttpRequest.post(Urls.getUrl(Urls.doComment + (type == 1 ? "video" : "image")), params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					showToast("评论成功");
					wonderfulAdapter.notifyDataSetChanged();
				} else {
					showToast("评论失败");
				}
			}
		});
	}

	private class WonderfulAdapter extends BaseViewHolderAdapter<Wonderful, Holder> {

		private WonderfulAdapter(Context context) {
			super(context);
		}

		@Override
		protected void bindViews(View convertView, Holder holder, Wonderful item) {
			holder.tv_school_name = convertView.findViewById(R.id.tv_school_name);
			holder.tv_time = convertView.findViewById(R.id.tv_time);
			holder.iv_img = convertView.findViewById(R.id.iv_img);
			holder.iv_video_thumbnail = convertView.findViewById(R.id.iv_video_thumbnail);
			holder.fl_video_contain = convertView.findViewById(R.id.fl_video_contain);
			holder.iv_to_start = convertView.findViewById(R.id.iv_to_start);
			holder.iv_zan = convertView.findViewById(R.id.iv_zan);
			holder.iv_cai = convertView.findViewById(R.id.iv_cai);
			holder.iv_comment = convertView.findViewById(R.id.iv_comment);
			holder.tv_zan_num = convertView.findViewById(R.id.tv_zan_num);
			holder.tv_cai_num = convertView.findViewById(R.id.tv_cai_num);
			holder.tv_comment_num = convertView.findViewById(R.id.tv_comment_num);
			holder.slv_comment_list = convertView.findViewById(R.id.slv_comment_list);
		}

		@Override
		protected View getConvertView(Wonderful item, LayoutInflater inflater, int position, ViewGroup parent) {
			return inflater.inflate(R.layout.item_wonderful_list, parent, false);
		}

		@Override
		protected Holder getHolder() {
			return new Holder();
		}

		@Override
		protected void refreshView(int position, Wonderful item, View convertView, Holder holder) {
			holder.iv_img.setVisibility(View.GONE);
			holder.fl_video_contain.setVisibility(View.GONE);
			((View) holder.slv_comment_list.getParent()).setVisibility(View.GONE);
			if (item.getType() == 1) {
				holder.fl_video_contain.setVisibility(View.VISIBLE);
				BaseImageLoad.load(item.getThumbnail(), holder.iv_video_thumbnail);
				holder.iv_to_start.setOnClickListener(v -> {
					Intent intent = new Intent(context, SimplePlayActivity.class);
					intent.putExtra("url", item.getFpath());
					context.startActivity(intent);
				});
			} else if (item.getType() == 2) {
				holder.iv_img.setVisibility(View.VISIBLE);
				BaseImageLoad.load(item.getFpath(), holder.iv_img);
				holder.iv_img.setOnClickListener(v -> ShowImageActivity.showImgById(context, item.getFpath()));
			}
			CacheManager.getInstance().getSchool(item.getSchoolId(), new CacheManager.HandleCallback<School>() {
				@Override
				public void onCacheSuccess(School result) {
					holder.tv_school_name.setText(result.getName());
				}

				@Override
				public void onHttpSuccess(School result) {
					holder.tv_school_name.setText(result.getName());
				}

				@Override
				public void onError() {
				}
			});
			holder.tv_zan_num.setText(String.valueOf(item.getPositives()));
			holder.tv_cai_num.setText(String.valueOf(item.getNegatives()));
			holder.tv_time.setText(DateUtil.dateToString(item.getTime()).substring(5, 16));

			holder.iv_zan.setSelected(PrefCache.getZan(item.getId(), type));
			holder.iv_zan.setOnClickListener(v -> doZan(item.getId(), (ImageView) v));
			holder.iv_cai.setSelected(PrefCache.getCai(item.getId(), type));
			holder.iv_cai.setOnClickListener(v -> doCai(item.getId(), (ImageView) v));
			holder.iv_comment.setOnClickListener(v -> {
				CommentDialog commentDialog = new CommentDialog(context, item.getId(), (content, dialog) -> {
					if (TextUtils.isEmpty(content)) {
						showToast("评论不能为空");
						return;
					}
					doComment(item.getId(), content);
					dialog.cancel();
				});
				commentDialog.show();
			});

			CacheManager.getInstance().getComment(item.getId(), type, new CacheManager.HandleCallback<List<Comment>>() {
				@Override
				public void onCacheSuccess(List<Comment> result) {
				}

				@Override
				public void onHttpSuccess(List<Comment> result) {
					CommentAdapter commentAdapter = new CommentAdapter(context);
					Collections.sort(result, (o1, o2) -> o1.getId() - o2.getId());
					commentAdapter.addListData(result);
					if (holder.slv_comment_list != null) {
						holder.slv_comment_list.setAdapter(commentAdapter);
					}
					holder.tv_comment_num.setText(String.valueOf(result.size()));
					if (result.size() > 0) {
						((View) holder.slv_comment_list.getParent()).setVisibility(View.VISIBLE);
					}
				}

				@Override
				public void onError() {
				}
			});


		}
	}

	private class Holder {
		TextView tv_school_name;
		TextView tv_time;
		ImageView iv_img;
		ImageView iv_video_thumbnail;
		FrameLayout fl_video_contain;
		ImageView iv_to_start;
		ImageView iv_zan;
		ImageView iv_cai;
		ImageView iv_comment;
		TextView tv_zan_num;
		TextView tv_cai_num;
		TextView tv_comment_num;
		NoScrollListView slv_comment_list;
	}

	private class CommentAdapter extends BaseViewHolderAdapter<Comment, CommentHolder> {

		private CommentAdapter(Context context) {
			super(context);
		}

		@Override
		protected void bindViews(View convertView, CommentHolder holder, Comment item) {
			holder.tv_comment_content = convertView.findViewById(R.id.tv_comment_content);
		}

		@Override
		protected View getConvertView(Comment item, LayoutInflater inflater, int position, ViewGroup parent) {
			return inflater.inflate(R.layout.item_comment_list, parent, false);
		}

		@Override
		protected CommentHolder getHolder() {
			return new CommentHolder();
		}

		@Override
		protected void refreshView(int position, Comment item, View convertView, CommentHolder holder) {
			SpannableStringBuilder style = new SpannableStringBuilder(item.getUsername() + "：" + item.getContent());
			style.setSpan(new ForegroundColorSpan(getColorBase(R.color.common_theme_text)), 0, item.getUsername().length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			holder.tv_comment_content.setText(style);
		}
	}

	private class CommentHolder {
		TextView tv_comment_content;
	}
}
